<?php

namespace App\Http\Controllers;

// use App\Console\Commands\mqtt;
use Workerman\Mqtt;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Redis;

class TestController extends Controller
{
    public function sendMessage(){
        // print_r('222');die;
        //.$users[0]['deviceId'].'&projectId='.$users[0]['projectId']
        $app = app('wechat.official_account');
	    $res = $app->template_message->send([
	        'touser' => 'os2gqwJxX8OXyhuoJxQ5HL_zr_ww',
	        'template_id' => 'wKqlkfSZPuy3G6iRzVAmlPtTVUvYDuN9WNuTNivMYpY',
	        'miniprogram' => [
	                'appid' => 'wx301bce58badb7cc3',
	                'pagepath' => 'pages/test/test?deviceId=18',
	        ],
	        'data' => [
	        	"first" => [
	        		"value"=>'设备出现异常请及时关注',
	        		"color"=>"#173177"
	        	],
	        	"keyword1" => [
                   "value"=>'2020-04-26 17:08:00',
                   "color"=>"#173177"
                ],
                "keyword2"=> [
                   "value"=>'设备',
                   "color"=>"#173177"
                ],
                "keyword3"=> [
                   "value"=>'报警内容',
                   "color"=>"#173177"
                ],
                "remark" => [
                	"value"=>'备注',
                	"color"=>"#173177"
                ]
	        ],
	    ]);
        print_r($res);die;
    }
    //十六进制转浮点数
    public function hexTo32Float($strHex) {
        $v = hexdec($strHex);
        $x = ($v & ((1 << 23) - 1)) + (1 << 23) * ($v >> 31 | 1);
        $exp = ($v >> 23 & 0xFF) - 127;
        return $x * pow(2, $exp - 23);
    }
    //开关状态地址0x0007 0：断开 1：闭合 2：分闸（分闸后不可手动合闸）
    public function index(){
        // $str = '{"SSN":"9D84210802135435","MRaw_Request":"9213 01D0 0006 03 06 01D0 0001"}';
        // print_r('str:'.$str.'</br>');
        // $res = json_decode($str,1);
        // $crc = substr($res['MRaw_Request'],0,4);
        // print_r('CRC: '.$crc.'</br>');
        // $start = substr($res['MRaw_Request'],4,4);
        // print_r('起始位: '.$start.'</br>');
        // $length = substr($res['MRaw_Request'],8,4);
        // print_r('长度: '.$length.'</br>');
        // $ji = substr($res['MRaw_Request'],12,2);
        // print_r('机位/地址位: '.$ji.'</br>');
        // $gn = substr($res['MRaw_Request'],14,2);
        // print_r('功能码: '.$gn.'</br>');
        // $what = substr($res['MRaw_Request'],16,4);
        // print_r('寄存器地址: '.$what.'</br>');
        // $aa = substr($res['MRaw_Request'],20,4);
        // print_r('数据1: '.$aa.'</br>');die;
        //set存数据 创建一个 key 并设置value 
        // Redis::del('FFF2211026162309'); 
        //get命令用于获取指定 key 的值,key不存在,返回null,如果key储存的值不是字符串类型，返回一个错误。
        // var_dump(Redis::get('FFF2211026162309'));die;
        // $result  = Artisan::call('mqtt_pub',['device'=>'FFF2211026162309','str'=>'01D00006010601D00004']);
        // print_r($result);die;
        // $array1 = array("current" => 10, 'voltage' => 2, 'temp' => 4);
        // $array2 = array("power" => 12, "status" => 1);
        // $result = array_merge($array1, $array2);
        // print_r($result);die;
        //{"SSN":"5CB3210912104109","MRaw_Request":"c24602500006020602500004"} 3P分闸
        //{"SSN":"5CB3210912104109","MRaw_Request":"024502500006020602500001"} 3P合闸
        //{"SSN":"5CB3210912104109","MRaw_Request":"838402500006020602500003"} 3P分闸不可手动合闸

        //{"SSN":"9D84210802135435","MRaw_Request":"1230 01D0 0006 030601D00003"} 1P分闸不可手动合闸
        //{"SSN":"9D84210802135435","MRaw_Request":"93f101D00006030601D00001"} 1P合闸
        //{"SSN":"9D84210802135435","MRaw_Request":"53f201D00006030601D00004"} 1P分闸
        // $src = '02500006020602500003';
        // $res = $this->modbus($src);//CRC
        // print_r($res.$src);die;
        // $info = 'D8580000002F01042C00020000000000000003000000150000003F00000000000000B3FBFA63A74EAB00000000000000000000001B';
        // $info = 'D836002C002B010428020185A2C0C90D000008000200000000000300030000000000000000001600000001FFFF3B3851EC';
        // $info = 'F9990000002F01042C00000000000000000003000000170000003F00000000000000B3FBFA63A74EAB00000000000000000000001B';
        // $info = '19980000002F01042C00000000000000000003000000150000003F00000000000000B3FBFA63A74EAB00000000000000000000001A';
        // {"SSN":"9D84210802135435","DataUp04":"19980000002F01042C00000000000000000003000000150000003F00000000000000B3FBFA63A74EAB00000000000000000000001A","TM":"301210234728"}
        //{"SSN":"9D84210802135435","DataUp04":"E40A002C002B010428020185A2C0C805000008000200000000000300030000000000000000001500010000FFFF3B3851EC","TM":"301210235054"}
        // print_r($info.'</br>');
        // $info = '{
        //     "SSN" : "9D84210802135435",
        //     "DataUp04" : "E4AC002C002B0104280205ADA3C4C80D00000A000200000002000300030000000000000000001A00010000FFFF3B3851EC",
        //     "TM" : "301221180101"
        //   }';
        $info = '{"SSN":"5CB3210912104109","DataUp04":"A1CA002C002F02042C000000010000000100000001000000051384095E04B30962000000E4000000005CB321091210410900000000","TM":"301202015200"}';
        // $info = '{"SSN":"9D84210802135435","DataUp04":"A9630000002F03042C00000000000000000003000100230000003F00000000000000B3FBFA63A74EAB000000000000436071DF0013","TM":"301201172316"}';
        // $info = '{
        //     "SSN" : "9D84210802135435",
        //     "DataUp04" : "E961002C002B0104281301ADA2C4C90D00000A000200000002000300030000000000000000001900010000FFFF3C828F5C",
        //     "TM" : "301221191122"
        //   }';
        // $info = '{"SSN":"9D84210802135435","DataUp04":"4016002C002B01042802018DA2C0C90D000008000200000000000300030000000000000000001700010000FFFF3B3851EC","TM":"301209220709"}';
        //CRC {"SSN":"9D84210802135435","DataUp04":"FD8B0016002F01042C000000003B3851EC00000000000000009D8421080213543598EDF6E500000000000000000000000081450047","TM":"301210175621"}
        //{"SSN":"9D84210802135435","DataUp04":"F999 0000 002F 01042C00000000000000000003000000170000003F00000000000000B3FBFA63A74EAB00000000000000000000001B","TM":"301210181451"}
        //{"SSN":"9D84210802135435","DataUp04":"D858 0000 002F 01042C00000000000000000003000000150000003F00000000000000B3FBFA63A74EAB00000000000000000000001B","TM":"301211000141"}
        $res = json_decode($info,1);
        $info = $res['DataUp04'];
        print_r('DataUp04 : '.$info.'</br>');
        $crc = substr($info,0,4);
        print_r('CRC：'.$crc.'</br>');
        //起始地址
        $start = hexdec(substr($info,4,4));
        //结束地址
        $end = hexdec(substr($info,8,4));
        print_r('起始位：'.substr($info,4,4).'</br>');
        print_r('寄存器个数：'.substr($info,8,4).'</br>');
        print_r('机位：'.substr($info,12,2).'</br>');
        //机位
        $c = substr($info,12,2);
        print_r('功能码：'.substr($info,14,2).'</br>');
        print_r('字节数: '.substr($info,16,2).'</br>');
        //功能码
        $function = substr($info,14,2);
        //字节数
        $code = substr($info,16,2);
        // print_r('功能码：'.substr($info,16,2).'</br>');
        //DataUp04
        $DataUp04 = str_split(substr($info,18),4);
        print_r('拆分：'.implode(',',$DataUp04).'</br>');
        $arr = [];
        foreach($DataUp04 as $key=>$val){
            $arr[$start+$key] = $val;
        }
        print_r('起始位开始键值对：');
        print_r('</br>');
        print_r($arr);
        print_r('</br>');
        
        if(isset($arr[8])&&isset($arr[9])){//16~17 A相有效电流
            $str = $arr[8].$arr[9];
            $aa = hexdec($str);
            $Current = $this->hexTo32Float($str);
            $param['a'] = $Current;
        }
        print_r($aa);
        print_r('</br>');
        print_r($arr[9]);die;
        if(isset($arr[16])&&isset($arr[17])){//16~17 电流
            $str = $arr[16].$arr[17];
            $Current = $this->hexTo32Float($str);
            $param['current'] = $Current;
        }
        if(isset($arr[19])&&isset($arr[20])){//19~20 电压
            $str = $arr[19].$arr[20];
            $Voltage = $this->hexTo32Float($str);
            $param['voltage'] = $Voltage;
        }
        if(isset($arr[21])){//21 温度
            $Temp = hexdec($arr[21]);
            $param['temp'] = $Temp;
        }
        if(isset($arr[22])&&isset($arr[23])){//22~23 功率
            $str = $arr[22].$arr[23];
            $Power = $this->hexTo32Float($str);
            $param['power'] = $Power;
        }
        if(isset($arr[29])){//29 开关状态 0：断开 1：闭合 2：分闸（分闸后不可手动合闸）
            $SwitchStatus = intval($arr[29]);
            $param['status'] = $SwitchStatus;
        }
        // print_r($arr);die;
        $count = count($DataUp04);
        // print_r('字节数：'.$count.'</br>');
        // str_split(string,length)
        print_r(implode(',',$DataUp04));die;
        //电流
        $Electriccurrent = '';
        //判断起始位置与结束位置是否包括电流、电压、温度
        print_r($function);die;
        // $mqtt = new \Workerman\Mqtt\Client('mqtt://218.85.129.211:1883',array('username' => 'hf-mqtt','password' => 'drd12345',));
        // $mqtt->onConnect = function($mqtt) {
        //     $mqtt->publish('hongfa/FFF2211026162309/download/','{"SSN":"9D84210802135435","MRaw_Request":"521001D00006010601D00001"}');
        //     $mqtt->close('hello\n');
        // };
        // $mqtt->onMessage = function($topic, $content){
        //     var_dump($topic, $content);
        // };
        // $mqtt->connect();
        // $res = hex2bin('C2A30016002F01042C000000003B3851EC00000000000000019D84210802135435B86DF6E400000000000000000000000081450047');
        // session()->put('device', 'FFF2211026162309');
        // $mqtt = new mqtt();
        // $mqtt->handle();
        // print_r($mqtt);die;
    }
    public function hexToDecFloat($strHex) {
        $v = hexdec($strHex);
        $x = ($v & ((1 << 23) - 1)) + (1 << 23) * ($v >> 31 | 1);
        $exp = ($v >> 23 & 0xFF) - 127;
        return $x * pow(2, $exp - 23);
    }
    public static function modbus($modbus_msg)
    {

        $crctab16 = [0X0000, 0XC0C1, 0XC181, 0X0140, 0XC301, 0X03C0, 0X0280, 0XC241,
            0XC601, 0X06C0, 0X0780, 0XC741, 0X0500, 0XC5C1, 0XC481, 0X0440,
            0XCC01, 0X0CC0, 0X0D80, 0XCD41, 0X0F00, 0XCFC1, 0XCE81, 0X0E40,
            0X0A00, 0XCAC1, 0XCB81, 0X0B40, 0XC901, 0X09C0, 0X0880, 0XC841,
            0XD801, 0X18C0, 0X1980, 0XD941, 0X1B00, 0XDBC1, 0XDA81, 0X1A40,
            0X1E00, 0XDEC1, 0XDF81, 0X1F40, 0XDD01, 0X1DC0, 0X1C80, 0XDC41,
            0X1400, 0XD4C1, 0XD581, 0X1540, 0XD701, 0X17C0, 0X1680, 0XD641,
            0XD201, 0X12C0, 0X1380, 0XD341, 0X1100, 0XD1C1, 0XD081, 0X1040,
            0XF001, 0X30C0, 0X3180, 0XF141, 0X3300, 0XF3C1, 0XF281, 0X3240,
            0X3600, 0XF6C1, 0XF781, 0X3740, 0XF501, 0X35C0, 0X3480, 0XF441,
            0X3C00, 0XFCC1, 0XFD81, 0X3D40, 0XFF01, 0X3FC0, 0X3E80, 0XFE41,
            0XFA01, 0X3AC0, 0X3B80, 0XFB41, 0X3900, 0XF9C1, 0XF881, 0X3840,
            0X2800, 0XE8C1, 0XE981, 0X2940, 0XEB01, 0X2BC0, 0X2A80, 0XEA41,
            0XEE01, 0X2EC0, 0X2F80, 0XEF41, 0X2D00, 0XEDC1, 0XEC81, 0X2C40,
            0XE401, 0X24C0, 0X2580, 0XE541, 0X2700, 0XE7C1, 0XE681, 0X2640,
            0X2200, 0XE2C1, 0XE381, 0X2340, 0XE101, 0X21C0, 0X2080, 0XE041,
            0XA001, 0X60C0, 0X6180, 0XA141, 0X6300, 0XA3C1, 0XA281, 0X6240,
            0X6600, 0XA6C1, 0XA781, 0X6740, 0XA501, 0X65C0, 0X6480, 0XA441,
            0X6C00, 0XACC1, 0XAD81, 0X6D40, 0XAF01, 0X6FC0, 0X6E80, 0XAE41,
            0XAA01, 0X6AC0, 0X6B80, 0XAB41, 0X6900, 0XA9C1, 0XA881, 0X6840,
            0X7800, 0XB8C1, 0XB981, 0X7940, 0XBB01, 0X7BC0, 0X7A80, 0XBA41,
            0XBE01, 0X7EC0, 0X7F80, 0XBF41, 0X7D00, 0XBDC1, 0XBC81, 0X7C40,
            0XB401, 0X74C0, 0X7580, 0XB541, 0X7700, 0XB7C1, 0XB681, 0X7640,
            0X7200, 0XB2C1, 0XB381, 0X7340, 0XB101, 0X71C0, 0X7080, 0XB041,
            0X5000, 0X90C1, 0X9181, 0X5140, 0X9301, 0X53C0, 0X5280, 0X9241,
            0X9601, 0X56C0, 0X5780, 0X9741, 0X5500, 0X95C1, 0X9481, 0X5440,
            0X9C01, 0X5CC0, 0X5D80, 0X9D41, 0X5F00, 0X9FC1, 0X9E81, 0X5E40,
            0X5A00, 0X9AC1, 0X9B81, 0X5B40, 0X9901, 0X59C0, 0X5880, 0X9841,
            0X8801, 0X48C0, 0X4980, 0X8941, 0X4B00, 0X8BC1, 0X8A81, 0X4A40,
            0X4E00, 0X8EC1, 0X8F81, 0X4F40, 0X8D01, 0X4DC0, 0X4C80, 0X8C41,
            0X4400, 0X84C1, 0X8581, 0X4540, 0X8701, 0X47C0, 0X4680, 0X8641,
            0X8201, 0X42C0, 0X4380, 0X8341, 0X4100, 0X81C1, 0X8081, 0X4040];

        $hexdata = pack("H*", $modbus_msg);
        $nLength = strlen($hexdata);
        $fcs = 0xFFFF;
        $pos = 0;
        while ($nLength > 0) {
            $fcs = ($fcs >> 8) ^ $crctab16[($fcs ^ ord($hexdata[$pos])) & 0xFF];
            $nLength--;
            $pos++;
        }
        $crc_semi_inverted = sprintf("%04x", $fcs);
        $crc_modbus = substr($crc_semi_inverted, 2, 2) . substr($crc_semi_inverted, 0, 2);
        return $crc_modbus;
    }

    public function essertest(){
        
        // $url = '/json/3.json';
        // $json = file(public_path($url));
        // $point = json_decode($json[0]);
        // foreach($point as $key => &$value){
        //     $val = json_decode($value,1);
        //     if($val['name']==$imei){
        //         $value['type'] = 3;
        //     }
        // }
        // print_r($point);die;
        // $str = '1c 25 24 35 54';
        // explode('54')
        $status  = ['0c'=>['status'=>0,'name'=>'电源故障','time'=>time()],
        '44'=>['status'=>0,'name'=>'开锁','time'=>time()],
        'c8'=>['status'=>0,'name'=>'回路故障','time'=>time()],'38'=>['status'=>0,'name'=>'技术报警','time'=>time()],
            '28' => ['7-13'=>['status'=>0,'name'=>'火警','time'=>time(),'str'=>'7-13']],'04' => ['7-12'=>['status'=>0,'name'=>'故障','time'=>time(),'str'=>'7-12']]];
        // Redis::set('192.168.2.102',json_encode($status));
        $data = json_decode(Redis::get('192.168.2.102'),1);
        print_r($data);
    }

    public function test(Request $request){
        $param = $request->all();
        $in_yan = $param['in_yan'];//870000//烟气量
        $in_fen = $param['in_fen'];//3//入口粉尘
        $shi = $param['shi'];//1//室数
        $high = $param['high'];//14.3;//电场有效高度
        $bu_fen1 = 4500;//捕集粉尘堆积密度
        $bu_fen2 = 100;//捕集粉尘堆积密度
        $bu_fen3 = 1.55;//捕集粉尘堆积密度
        $bu_fen4 = 0.06;//捕集粉尘堆积密度
        $jichen = $param['jichen'];//2.5;//积尘厚度
        $N = 4;//电场数
        $K = 0.167;//通用系数
        if($param['xiao']){
            $xiao1 = $param['xiao']/100;
            $xiao2 = $param['xiao']/100;
            $xiao3 = $param['xiao']/100;
            $xiao4 = $param['xiao']/100;
        }else{
            $xiao1 = 0.87;//1电场除尘效率
            $xiao2 = 0.87;//2电场除尘效率
            $xiao3 = 0.87;//3电场除尘效率
            $xiao4 = 0.87;//4电场除尘效率
        }
        if($param['tong']){
            $tong1 = $param['tong'];
            $tong2 = $param['tong'];
            $tong3 = $param['tong'];
            $tong4 = $param['tong'];
        }else{
            $tong1 = 40;//1电场通道数
            $tong2 = 40;//2电场通道数
            $tong3 = 40;//3电场通道数
            $tong4 = 40;//4电场通道数
        }
        if($param['length']){
            $length1 = $param['length'];
            $length2 = $param['length'];
            $length3 = $param['length'];
            $length4 = $param['length'];
        }else{
            $length1 = 4;//1电场长度
            $length2 = 4;//2电场长度
            $length3 = 4;//3电场长度
            $length4 = 4;//4电场长度
        }
        $shou1 = $shi*$high*($tong1*$length1);//1电场的收尘面积
        $shou2 = $shi*$high*($tong2*$length2);//2电场的收尘面积
        $shou3 = $shi*$high*($tong3*$length3);//3电场的收尘面积
        $shou4 = $shi*$high*($tong4*$length4);//4电场的收尘面积
        $yangj1 = 120;//1电场阳极振打间隙时间
        $yangj2 = 300;//2电场阳极振打间隙时间
        $yangj3 = 480;//3电场阳极振打间隙时间
        $yangj4 = 1800;//4电场阳极振打间隙时间
        $yinj1 = 360;//1电场阴极振打间隙时间 
        $yinj2 = 400;//2电场阴极振打间隙时间 
        $yinj3 = 600;//3电场阴极振打间隙时间 
        $yinj4 = 800;//4电场阴极振打间隙时间 
        $d1 = 0.4*$K*$in_fen*$in_yan;
        $t1 = $jichen*$shou1*$bu_fen1/$d1;//$K*$in_yan*$in_fen*(1-pow(0.1,1/4));
        $d2 = 0.4*$K*($in_fen-$in_fen*0.9)*($in_yan-$in_yan*0.9);
        $t2 = $jichen*$shou2*$bu_fen2/$d2;
        $d3 = 0.4*$K*(($in_fen-$in_fen*0.9)-($in_fen-$in_fen*0.9)*0.9)*(($in_yan-$in_yan*0.9)-($in_yan-$in_yan*0.9)*0.9);
        $t3 = $jichen*$shou3*$bu_fen3/$d3;
        $d4 = 0.4*$K*((($in_fen-$in_fen*0.9)-($in_fen-$in_fen*0.9)*0.9)-(($in_fen-$in_fen*0.9)-($in_fen-$in_fen*0.9)*0.9)*0.9)*((($in_yan-$in_yan*0.9)-($in_yan-$in_yan*0.9)*0.9)-(($in_yan-$in_yan*0.9)-($in_yan-$in_yan*0.9)*0.9)*0.9);
        $t4 = $jichen*$shou4*$bu_fen4/$d4;
        //$aa = rand(10,100);
        $arr = ['code'=>'100','data'=>['t1'=>intval($t1),'t2'=>intval($t2),'t3'=>intval($t3),'t4'=>intval($t4)]];
        return $arr;
    }

    function squre($number ,$t){
        $x1 = $number;
        $x2 = $number/2;
        while( abs($x1 - $x2) > $t){
            $x1 = $x2;
            $x2 = ($x1 + $number/$x1)/2;
        }
        return $x2;
    }

}